﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using VisualWip.Core.Utils;

namespace VisualWip.TFS2010PersistanceProvider
{
    public class SaveDialogViewModel : INotifyPropertyChanged
    {
        private string _path;
        private bool _saveEnabled;

        public SaveDialogViewModel(ObservableCollection<TFSConnectionSettingsPathView> tfsConnectionSettingsPathViews)
        {
            Settings = tfsConnectionSettingsPathViews;
            foreach (TFSConnectionSettingsPathView settingsPathView in Settings)
            {
                settingsPathView.PropertyChanged += SettingPropertyChanged;
            }
        }

        public ObservableCollection<TFSConnectionSettingsPathView> Settings { get; private set; }

        public string Path
        {
            get { return _path; }
            set
            {
                if (value != _path)
                {
                    _path = value;
                    OnPropertyChanged(this, () => Path);
                    SaveEnabled = !string.IsNullOrWhiteSpace(_path);
                }
            }
        }

        public bool SaveEnabled
        {
            get { return _saveEnabled; }
            set
            {
                if (value != _saveEnabled)
                {
                    _saveEnabled = value;
                    OnPropertyChanged(this, () => SaveEnabled);
                }
            }
        }

        public bool IsReplacing
        {
            get { return Settings.FirstOrDefault(x => StringComparer.InvariantCulture.Compare(x.Name, Path) == 0) != null; }
        }

        private void SettingPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            var settingsPathView = sender as TFSConnectionSettingsPathView;
            if (settingsPathView != null && settingsPathView.IsSelected)
                Path = settingsPathView.Name;
        }

        protected void OnPropertyChanged<T>(object sender, Expression<Func<T>> property)
        {
            PropertyHelper.OnPropertyChanged(sender, PropertyChanged, property);
        }

        #region Implementation of INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }
}